package la.iok.hzsvn.lewin.movie.service;

import la.iok.hzsvn.lewin.movie.obs.ObsService;
import la.iok.hzsvn.share.dfs.exception.DfsException;
import la.iok.hzsvn.share.dfs.model.DfsDescriptor;
import la.iok.hzsvn.share.dfs.model.DfsResult;
import la.iok.hzsvn.share.dfs.service.AbstractDfsService;

import java.io.File;
import java.io.OutputStream;
import java.util.UUID;

public class HuaweiObsFileSystemServiceImpl extends AbstractDfsService {
    private final ObsService obsService;

    public HuaweiObsFileSystemServiceImpl(ObsService obsService) {
        this.obsService = obsService;
    }

    @Override
    public DfsResult uploadFile(String storePath, File file) throws DfsException {
        obsService.uploadFile(storePath,file);
        return DfsResult.success(dfsFile(storePath));
    }

    @Override
    public DfsResult downloadFile(OutputStream outputStream, DfsDescriptor descriptor) throws DfsException {
        obsService.downloadFile(descriptor.path(),outputStream);
        return DfsResult.success(descriptor);
    }

    @Override
    public DfsResult deleteFile(DfsDescriptor descriptor) throws DfsException {
        obsService.deleteFile(descriptor.path());
        return DfsResult.success(descriptor);
    }

    @Override
    public DfsDescriptor dfsFile(String path) {
        return new HuaweiObsFileDescriptor(path);
    }

    @Override
    public String storePath(String digest, String fileName) {
        String id;
        String path;
        do {
            id = UUID.randomUUID().toString().replaceAll("-","");
            path = defaultStorePath(id,fileName);
        }while (obsService.exist(path));
        return path;
    }

    @Override
    public long getFileLength(DfsDescriptor descriptor) {
        return obsService.fileLength(descriptor.path());
    }

    @Override
    public boolean exist(DfsDescriptor descriptor) {
        return obsService.exist(descriptor.path());
    }

    public static class HuaweiObsFileDescriptor implements DfsDescriptor{
        private final String objKey;
        public HuaweiObsFileDescriptor(String objKey){
            this.objKey = objKey;
        }
        @Override
        public String path() {
            return objKey;
        }
    }
}
